package com.atguigu.flink.chapter07;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/12/15 9:26
 */
public class Flink16_ProccessingTime {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

        env.setParallelism(1);

        SingleOutputStreamOperator<String> mainStream = env
                .socketTextStream("hadoop162", 9999)
                .map(line -> {
                    String[] strings = line.split(",");
                    return new WaterSensor(strings[0], Long.valueOf(strings[1]), Integer.valueOf(strings[2]));
                })
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    private long timer;

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        System.out.println("timestamp:"+timestamp);
                        out.collect("有传感器水位超过50，发出黄色预警");
                    }
                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                        //注册定时器
                        // 水位超过50，则5秒之后发出预警信息

                        if (value.getVc() >=50) {

                            timer = ctx.timerService().currentProcessingTime()+5000;
                            System.out.println("timer:"+ timer);

                            ctx.timerService().registerProcessingTimeTimer(timer);

                        }else if (value.getVc()<= 20){
                            ctx.timerService().deleteProcessingTimeTimer(timer);
                        }
                    }



                })
               ;
        mainStream.print("s1");
//        mainStream.getSideOutput(new OutputTag<String>("s22"){}).print("s2");

        env.execute();
    }
/*
*       flink 如何做到数据不丢失
*       1.事件时间 + 水印
*       2，允许迟到
*       3.侧输出流
*
* */


}
